package com.wxzz.elearing.user.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.wxzz.elearing.user.amqp.producer.UserMessageProducer;
import com.wxzz.elearing.user.dto.*;
import com.wxzz.elearing.user.entity.*;
import com.wxzz.elearing.user.mapper.*;
import com.wxzz.elearing.user.service.IEnterpriseService;
import com.wxzz.elearing.user.service.IWxUserService;
import com.wxzz.elearing.user.service.openfeign.IEvaluationApiFeign;
import com.wxzz.elearning.common.bean.SmsConfig;
import com.wxzz.elearning.common.constants.RedisConstants;
import com.wxzz.elearning.common.dto.FeignEnterpriseDto;
import com.wxzz.elearning.common.dto.FeignWxUserDto;
import com.wxzz.elearning.common.dto.SystemMessageMqDto;
import com.wxzz.elearning.common.exception.ServiceException;
import com.wxzz.elearning.common.utils.BeanCompare;
import com.wxzz.elearning.common.utils.ExcelUtils;
import com.wxzz.elearning.common.utils.MD5Util;
import com.wxzz.elearning.common.utils.OpenFeignUtil;
import com.wxzz.elearning.common.vo.JgPageVo;
import com.wxzz.elearning.common.vo.ReturnVO;
import lombok.SneakyThrows;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * <p>
 * 企业 服务实现类
 * </p>
 *
 * @author
 * @since 2021-04-01
 */
@Service
public class EnterpriseServiceImpl extends ServiceImpl<EnterpriseMapper, Enterprise> implements IEnterpriseService {

    @Autowired
    private EnterpriseMapper enterpriseMapper;

    @Autowired
    private AdminUserMapper adminUserMapper;

    @SneakyThrows
    @Transactional
    @Override
    public ReturnVO<Long> saveEnterprise(Enterprise enterprise) {
        if (StringUtils.isBlank(enterprise.getUsername()) || StringUtils.isBlank(enterprise.getPassword())) {
            throw new ServiceException("账号或密码不能为空");
        }
        //新增企业
        if (enterprise.getId() == null) {
            enterpriseMapper.insert(enterprise);
            //新增企业账号
            AdminUser exist = adminUserMapper.selectOne(new LambdaQueryWrapper<AdminUser>().eq(AdminUser::getUsername, enterprise.getUsername()));
            if (exist != null) {
                throw new ServiceException("该账号已存在");
            }
            AdminUser adminUser = new AdminUser();
            adminUser.setPhone(enterprise.getLegalPersonPhone());
            adminUser.setUsername(enterprise.getUsername());
            adminUser.setEnterpriseId(enterprise.getId());
            //设置admin
            adminUser.setIsAdmin(1);
            adminUser.setPassword(MD5Util.md5Encrypt32Upper(enterprise.getPassword()));
            adminUser.setType(1);
            adminUserMapper.insert(adminUser);
            addAllRole(adminUser.getId(), enterprise.getId());
        } else {
//            AdminUser exist = adminUserMapper.selectOne(new LambdaQueryWrapper<AdminUser>().eq(AdminUser::getUsername, enterprise.getUsername()));
//            if (exist != null && !exist.getEnterpriseId().equals(enterprise.getId())) {
//                throw new ServiceException("该帐号已存在");
//            }
//            AdminUser adminUser = adminUserMapper.selectOne(new LambdaQueryWrapper<AdminUser>()
//                    .eq(AdminUser::getEnterpriseId, enterprise.getId())
//                    .eq(AdminUser::getIsAdmin, 1));
//            Optional.ofNullable(adminUser).orElseThrow(() -> new ServiceException("该企业无admin帐号"));
//            adminUser.setPhone(enterprise.getPhone());
//            adminUser.setPassword(MD5Util.md5Encrypt32Upper(enterprise.getPassword()));
//            //查出原数据
//            Enterprise oldEnterprise = enterpriseMapper.selectById(enterprise.getId());
//            oldEnterprise.setPhone(adminUser.getPhone());
//            oldEnterprise.setPassword(adminUser.getPassword());
//            //与原数据进行匹配
//            List<Map<String, String>> listData = BeanCompare.getListData(enterprise, oldEnterprise);
//            Enterprise enterpriseUpdateLog = BeanCompare.mapToBean(listData.get(0), Enterprise.class);
//            String logDetail = "";
//            if (enterpriseUpdateLog.getEnterpriseName() != null) {
//                logDetail = logDetail + "企业名称修改为:" + enterpriseUpdateLog.getEnterpriseName();
//            }
//            if (enterpriseUpdateLog.getCreditCode() != null) {
//                logDetail = logDetail + "统一社会信用代码修改为:" + enterpriseUpdateLog.getCreditCode();
//            }
//            if (enterpriseUpdateLog.getBusinessCategoryId() != null) {
//                ReturnVO<String> stringReturnVO = evaluationApiFeign.selectBusinessCategoryById(enterpriseUpdateLog.getBusinessCategoryId());
//                JSONObject jsonObject = OpenFeignUtil.getJSONObject(stringReturnVO);
//                logDetail = logDetail + "行业类目修改为:" + jsonObject.getString("categoryName");
//            }
//            if (enterpriseUpdateLog.getLegalPersonName() != null) {
//                logDetail = logDetail + "法人姓名修改为:" + enterpriseUpdateLog.getLegalPersonName();
//            }
//            if (enterpriseUpdateLog.getEnterpriseDetail() != null) {
//                logDetail = logDetail + "企业详细介绍富文本修改为:" + enterpriseUpdateLog.getEnterpriseDetail();
//            }
//            if (enterpriseUpdateLog.getEnterprisePlace() != null) {
//                logDetail = logDetail + "所属地区修改为:" + enterpriseUpdateLog.getEnterprisePlace();
//            }
//            if (enterpriseUpdateLog.getEnterprisePlaceDetail() != null) {
//                logDetail = logDetail + "企业详细地址修改为:" + enterpriseUpdateLog.getEnterprisePlaceDetail();
//            }
//            if (enterpriseUpdateLog.getEnterpriseLogo() != null) {
//                logDetail = logDetail + "企业logo修改为:" + enterpriseUpdateLog.getEnterpriseLogo();
//            }
//            if (enterpriseUpdateLog.getPhone() != null) {
//                logDetail = logDetail + "企业绑定手机号修改为:" + enterpriseUpdateLog.getPhone();
//            }
//            if (enterpriseUpdateLog.getPassword() != null) {
//                logDetail = logDetail + "密码被修改";
//            }
//            //插入操作日志
//            if (StringUtils.isNotBlank(logDetail)) {
//                EnterpriseUpdateLog updateLog = new EnterpriseUpdateLog();
//                updateLog.setEnterpriseId(enterprise.getId());
//                enterpriseUpdateLogMapper.insert(updateLog);
//            }
//            //更新
//            adminUserMapper.updateById(adminUser);
//            enterpriseMapper.updateById(enterprise);
//            if (enterprise.getIsBan() == 1) {
//                //通知封禁
//                WxUser wxUser = wxUserMapper.selectById(enterprise.getWxUserId());
//                if (wxUser != null) {
//                    SystemMessageMqDto systemMessageMqDto = new SystemMessageMqDto();
//                    if (enterprise.getIsSms() != null && enterprise.getIsSms() == 1) {
//                        systemMessageMqDto.setPhones(new ArrayList<String>() {
//                            {
//                                add(wxUser.getPhone());
//                            }
//                        });
//                        systemMessageMqDto.setTemplateId(SmsConfig.enterpriseBanId);
//                        systemMessageMqDto.setParams(new ArrayList<String>() {
//                            {
//                                add(enterprise.getEnterpriseName());
//                                add(LocalDate.now().toString());
//                                add(LocalDateTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")));
//                            }
//                        });
//                    }
//                    systemMessageMqDto.setMessageDetail(enterprise.getBanReason());
//                    systemMessageMqDto.setMessageTitle("企业封禁");
//                    systemMessageMqDto.setWxUserIds(new ArrayList<Long>() {
//                        {
//                            add(wxUser.getId());
//                        }
//                    });
//                    userMessageProducer.ackMQSender(JSONObject.toJSONString(systemMessageMqDto));
//                }
//            }
        }
        return new ReturnVO("企业账号新增或修改成功", enterprise.getId());
    }

    @Autowired
    private EnterpriseUpdateLogMapper enterpriseUpdateLogMapper;

    @Autowired
    private AdminRoleMapper adminRoleMapper;

    @Autowired
    private AdminUserRoleMapper adminUserRoleMapper;

    @Autowired
    private AdminPermissionMapper adminPermissionMapper;

    @Autowired
    private AdminRolePermissionMapper adminRolePermissionMapper;

    /**
     * 添加admin角色
     *
     * @param adminUserId
     * @param enterpriseId
     */
    @Transactional
    public void addAllRole(Long adminUserId, Long enterpriseId) {
        //创建角色
        AdminRole adminRole = new AdminRole();
        adminRole.setRemark("默认角色");
        adminRole.setRoleName("admin");
        adminRole.setEnterpriseId(enterpriseId);
        adminRole.setRoleType(1);
        adminRoleMapper.insert(adminRole);
        //角色关联用户
        AdminUserRole adminUserRole = new AdminUserRole();
        adminUserRole.setAdminUserId(adminUserId);
        adminUserRole.setAdminRoleId(adminRole.getId());
        adminUserRoleMapper.insert(adminUserRole);
        //查询所有权限
        List<AdminPermission> permissions = adminPermissionMapper.selectList(new LambdaQueryWrapper<AdminPermission>()
                .eq(AdminPermission::getPermissionType, 1));
        for (AdminPermission permission : permissions) {
            //给角色分配权限
            AdminRolePermission adminRolePermission = new AdminRolePermission();
            adminRolePermission.setAdminRoleId(adminRole.getId());
            adminRolePermission.setAdminPermissionId(permission.getId());
            adminRolePermissionMapper.insert(adminRolePermission);
        }
    }

    @SneakyThrows
    @Override
    public ReturnVO updateEnterprise(JSONObject jsonObject, Enterprise enterprise) {
        AdminUser exist = adminUserMapper.selectOne(new LambdaQueryWrapper<AdminUser>().eq(AdminUser::getUsername, enterprise.getUsername()));
        if (exist != null && !exist.getEnterpriseId().equals(enterprise.getId())) {
            throw new ServiceException("该帐号已存在");
        }
        AdminUser adminUser = adminUserMapper.selectOne(new LambdaQueryWrapper<AdminUser>()
                .eq(AdminUser::getEnterpriseId, enterprise.getId())
                .eq(AdminUser::getIsAdmin, 1));
        Optional.ofNullable(adminUser).orElseThrow(() -> new ServiceException("该企业无admin帐号"));
        adminUser.setPhone(enterprise.getPhone());
        if (enterprise.getPassword() != null) {
            adminUser.setPassword(MD5Util.md5Encrypt32Upper(enterprise.getPassword()));
        }
        //查出原数据
        Enterprise oldEnterprise = enterpriseMapper.selectById(enterprise.getId());
        oldEnterprise.setPhone(adminUser.getPhone());
        if (enterprise.getPassword() != null) {
            oldEnterprise.setPassword(MD5Util.md5Encrypt32Upper(enterprise.getPassword()));
        }
        //与原数据进行匹配
        List<Map<String, String>> listData = BeanCompare.getListData(enterprise, oldEnterprise);
        String logDetail = "";
        if (listData.get(0).get("enterpriseName") != null) {
            logDetail = logDetail + "  企业名称修改为:" + listData.get(0).get("enterpriseName");
        }
        if (listData.get(0).get("creditCode") != null) {
            logDetail = logDetail + "  统一社会信用代码修改为:" + listData.get(0).get("creditCode");
        }
        if (listData.get(0).get("businessCategoryId") != null) {
            ReturnVO<String> stringReturnVO = evaluationApiFeign.selectBusinessCategoryById(Long.valueOf(listData.get(0).get("businessCategoryId")));
            if ("200".equals(stringReturnVO.getCode())) {
                logDetail = logDetail + "  企业行业修改为:" + stringReturnVO.getData();
            }
        }
        if (listData.get(0).get("personName") != null) {
            logDetail = logDetail + "  法人姓名修改为:" + listData.get(0).get("personName");
        }
        if (listData.get(0).get("enterpriseDetail") != null) {
            logDetail = logDetail + "  企业详细介绍富文本修改为:" + listData.get(0).get("enterpriseDetail");
        }
        if (listData.get(0).get("enterprisePlace") != null) {
            logDetail = logDetail + "  所属地区修改为:" + listData.get(0).get("enterprisePlace");
        }
        if (listData.get(0).get("enterprisePlaceDetail") != null) {
            logDetail = logDetail + "  企业详细地址修改为:" + listData.get(0).get("enterprisePlaceDetail");
        }
        if (listData.get(0).get("enterpriseLogo") != null) {
            logDetail = logDetail + "  企业logo修改为:" + listData.get(0).get("enterpriseLogo");
        }
        if (listData.get(0).get("phone") != null) {
            logDetail = logDetail + "  企业绑定手机号修改为:" + listData.get(0).get("phone");
        }
        if (listData.get(0).get("password") != null) {
            logDetail = logDetail + "  密码被修改";
        }
        //插入操作日志
        if (StringUtils.isNotBlank(logDetail)) {
            EnterpriseUpdateLog updateLog = new EnterpriseUpdateLog();
            updateLog.setEnterpriseId(enterprise.getId());
            updateLog.setAdminUserId(jsonObject.getLong("id"));
            updateLog.setUsername(jsonObject.getString("username"));
            updateLog.setLogDetail(logDetail);
            enterpriseUpdateLogMapper.insert(updateLog);
        }
        //更新
        adminUserMapper.updateById(adminUser);
        enterpriseMapper.updateById(enterprise);
        Enterprise select = enterpriseMapper.selectById(enterprise.getId());
        if (enterprise.getIsBan() != null && enterprise.getIsBan() == 1) {
            //通知封禁
            WxUser wxUser = wxUserMapper.selectById(select.getWxUserId());
            if (wxUser != null) {
                SystemMessageMqDto systemMessageMqDto = new SystemMessageMqDto();
                if (enterprise.getIsSms() != null && enterprise.getIsSms() == 1) {
                    systemMessageMqDto.setPhones(new ArrayList<String>() {
                        {
                            add(wxUser.getPhone());
                        }
                    });
                    systemMessageMqDto.setTemplateId(SmsConfig.enterpriseBanId);
                    systemMessageMqDto.setParams(new ArrayList<String>() {
                        {
                            add(select.getEnterpriseName());
                            add(LocalDate.now().toString());
                            add(LocalDateTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")));
                        }
                    });
                }
                systemMessageMqDto.setMessageDetail(enterprise.getBanReason());
                systemMessageMqDto.setMessageTitle("企业封禁");
                systemMessageMqDto.setWxUserIds(new ArrayList<Long>() {
                    {
                        add(wxUser.getId());
                    }
                });
                userMessageProducer.ackMQSender(JSONObject.toJSONString(systemMessageMqDto));
            }
        }
        //解禁
        if (enterprise.getIsBan() != null && enterprise.getIsBan().equals(0) && !oldEnterprise.getIsBan().equals(enterprise.getIsBan())) {
            //通知解禁
            WxUser wxUser = wxUserMapper.selectById(select.getWxUserId());
            if (wxUser != null) {
                SystemMessageMqDto systemMessageMqDto = new SystemMessageMqDto();
                if (enterprise.getIsSms() != null && enterprise.getIsSms() == 1) {
                    systemMessageMqDto.setPhones(new ArrayList<String>() {
                        {
                            add(wxUser.getPhone());
                        }
                    });
                    systemMessageMqDto.setTemplateId(SmsConfig.enterpriseUnBanId);
                    systemMessageMqDto.setParams(new ArrayList<String>() {
                        {
                            add(select.getEnterpriseName());
                            add(LocalDate.now().toString());
                            add(LocalDateTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")));
                        }
                    });
                }
                systemMessageMqDto.setMessageDetail("您在五星制造平台的" + select.getEnterpriseName() + "时被解封");
                systemMessageMqDto.setMessageTitle("企业解封");
                systemMessageMqDto.setWxUserIds(new ArrayList<Long>() {
                    {
                        add(wxUser.getId());
                    }
                });
                userMessageProducer.ackMQSender(JSONObject.toJSONString(systemMessageMqDto));
            }
        }
        return new ReturnVO("企业修改成功", enterprise.getId());
    }

    @Override
    public ReturnVO<JgPageVo<List<EnterpriseUpdateLog>>> listEnterpriseUpdateLog(EnterpriseUpdateLogDto enterpriseUpdateLogDto) {
        PageHelper.startPage(enterpriseUpdateLogDto.getCurPage(), enterpriseUpdateLogDto.getMaxPage());
        QueryWrapper<EnterpriseUpdateLog> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("create_time");
        queryWrapper.eq("enterprise_id", enterpriseUpdateLogDto.getEnterpriseId());
        if (StringUtils.isNotBlank(enterpriseUpdateLogDto.getUsername())) {
            queryWrapper.like("username", enterpriseUpdateLogDto.getUsername() + "%");
        }
        List<EnterpriseUpdateLog> enterpriseUpdateLogs = enterpriseUpdateLogMapper.selectList(queryWrapper);
        return new ReturnVO("企业操作查询成功", new JgPageVo<>(new PageInfo(enterpriseUpdateLogs)));
    }

    @Autowired
    private UserMessageProducer userMessageProducer;

    @Autowired
    private IEvaluationApiFeign evaluationApiFeign;

    @SneakyThrows
    @Override
    public ReturnVO<JgPageVo<List<Enterprise>>> listEnterprise(HttpServletResponse response, EnterpriseDto enterpriseDto) {
        PageHelper.startPage(enterpriseDto.getCurPage(), enterpriseDto.getMaxPage());
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.orderByDesc("create_time");
        if (StringUtils.isNotBlank(enterpriseDto.getEnterpriseName())) {
            queryWrapper.like("enterprise_name", enterpriseDto.getEnterpriseName() + "%");
        }
        if (enterpriseDto.getEnterpriseLevel() != null) {
            queryWrapper.eq("enterprise_level", enterpriseDto.getEnterpriseLevel());
        }
        if (enterpriseDto.getBusinessCategoryId() != null) {
            queryWrapper.eq("business_category_id", enterpriseDto.getBusinessCategoryId());
        }
        if (enterpriseDto.getStartTime() != null && enterpriseDto.getEndTime() != null) {
            queryWrapper.between("create_time", enterpriseDto.getStartTime(), enterpriseDto.getEndTime());
        }
        List<Enterprise> enterprises = enterpriseMapper.selectList(queryWrapper);
        //查询行业类目id
        for (Enterprise enterprise : enterprises) {
            if (enterprise.getBusinessCategoryId() != null) {
                ReturnVO<String> stringReturnVO = evaluationApiFeign.selectBusinessCategoryById(enterprise.getBusinessCategoryId());
                if ("200".equals(stringReturnVO.getCode())) {
                    enterprise.setCategoryName(stringReturnVO.getData());
                }
            }
        }
        if (enterpriseDto.getIsExport() != null && enterpriseDto.getIsExport() == 1) {
            ExcelUtils.exportExcel(enterprises, "企业列表", "企业列表", Enterprise.class, "企业列表", response);
            return new ReturnVO("企业列表导出成功", null);
        }
        return new ReturnVO("企业列表查询成功", new JgPageVo<>(new PageInfo(enterprises)));
    }

    @Override
    public ReturnVO enterpriseUpdateWxUser(Long enterpriseId, EnterpriseUpdateWxUserDto enterpriseUpdateWxUserDto) {
        Enterprise enterprise = enterpriseMapper.selectById(enterpriseId);
        Optional.ofNullable(enterprise).orElseThrow(() -> new ServiceException("企业不存在"));
        //院长信息
        WxUser wxUser = wxUserMapper.selectById(enterprise.getWxUserId());
        Optional.ofNullable(wxUser).orElseThrow(() -> new ServiceException("该企业没有院长"));
        if (StringUtils.isBlank(wxUser.getPhone())) {
            throw new ServiceException("原院长没有手机号");
        }
        String code = redisTemplate.opsForValue().get(RedisConstants.PHONE_CODE + enterpriseId + ":" + wxUser.getPhone());
        if (StringUtils.isBlank(code)) {
            throw new ServiceException("验证码失效");
        }
        if (!enterpriseUpdateWxUserDto.getCode().equals(code)) {
            throw new ServiceException("验证码错误");
        }
        enterprise.setWxUserId(enterpriseUpdateWxUserDto.getWxUserId());
        enterpriseMapper.updateById(enterprise);
        return new ReturnVO("院长改绑成功", null);
    }

    @Override
    public ReturnVO<Enterprise> selectEnterpriseDetail(Long enterpriseId) {
        Enterprise enterprise = enterpriseMapper.selectById(enterpriseId);
        Optional.ofNullable(enterprise).orElseThrow(() -> new ServiceException("该企业id对应企业不存在"));
        //回显企业admin的账号密码
        AdminUser adminUser = adminUserMapper.selectOne(new LambdaQueryWrapper<AdminUser>()
                .eq(AdminUser::getEnterpriseId, enterprise.getId())
                .eq(AdminUser::getIsAdmin, 1));
        if (adminUser != null) {
            enterprise.setPhone(adminUser.getPhone());
            enterprise.setUsername(adminUser.getUsername());
            enterprise.setPassword(adminUser.getPassword());
        }
        //行业类目
        if (enterprise.getBusinessCategoryId() != null) {
            ReturnVO<String> stringReturnVO = evaluationApiFeign.selectBusinessCategoryById(enterprise.getBusinessCategoryId());
            if ("200".equals(stringReturnVO.getCode())) {
                enterprise.setCategoryName(stringReturnVO.getData());
            }
        }
        //院长信息
        WxUser wxUser = wxUserMapper.selectById(enterprise.getWxUserId());
        if (wxUser != null) {
            enterprise.setNickname(wxUser.getNickname());
            FeignWxUserDto feignWxUserDto = wxUserService.selectFeignWxUserDtoByWxUserId(wxUser.getId());
            enterprise.setOrganizationName(feignWxUserDto.getIdentityName());
        }
        return new ReturnVO("企业详情查询成功", enterprise);
    }

    @Autowired
    private IWxUserService wxUserService;

    @Autowired
    private WxUserMapper wxUserMapper;

    @Override
    public ReturnVO<String> selectEnterpriseByWxUserId(Long wxUserId) {
        WxUser wxUser = wxUserMapper.selectById(wxUserId);
        if (wxUser == null) {
            throw new ServiceException("该id对应用户不存在");
        }
        if (wxUser.getEnterpriseId() == null) {
            throw new ServiceException("该用户无企业");
        }
        Enterprise enterprise = enterpriseMapper.selectById(wxUser.getEnterpriseId());
        return new ReturnVO("企业信息查询成功", JSONObject.toJSONString(enterprise));
    }

    @Autowired
    private EnterpriseIdentityMapper enterpriseIdentityMapper;

    @Autowired
    private EnterpriseOrganizationMapper enterpriseOrganizationMapper;

    @Override
    public ReturnVO<String> selectWxUserByWxUserId(Long wxUserId) {
        WxUser wxUser = wxUserMapper.selectById(wxUserId);
        if (wxUser == null) {
            throw new ServiceException("该id对应用户不存在");
        }
        //企业名称
        Enterprise enterprise = enterpriseMapper.selectById(wxUser.getEnterpriseId());
        if (enterprise != null) {
            wxUser.setEnterpriseName(enterprise.getEnterpriseName());
        }
        //部门名称
        if (wxUser.getEnterpriseOrganizationId() != null) {
            EnterpriseOrganization enterpriseOrganization = enterpriseOrganizationMapper.selectById(wxUser.getEnterpriseOrganizationId());
            if (enterpriseOrganization != null) {
                wxUser.setOrganizationName(enterpriseOrganization.getOrganizationName());
            }
        }
        //职位名称
        if (wxUser.getEnterpriseIdentityId() != null) {
            EnterpriseIdentity enterpriseIdentity = enterpriseIdentityMapper.selectById(wxUser.getEnterpriseIdentityId());
            if (enterpriseIdentity != null) {
                wxUser.setIdentityName(enterpriseIdentity.getIdentityName());
            }
        }
        return new ReturnVO("微信用户信息查询成功", JSONObject.toJSONString(wxUser));
    }

    @Override
    public ReturnVO<String> selectEnterpriseById(Long enterpriseId) {
        Enterprise enterprise = enterpriseMapper.selectById(enterpriseId);
        return new ReturnVO("企业信息查询成功", JSONObject.toJSONString(enterprise));
    }

    @Override
    public ReturnVO<Long> selectBusinessCategoryIdByEnterpriseId(Long enterpriseId) {
        Enterprise enterprise = enterpriseMapper.selectById(enterpriseId);
        Optional.ofNullable(enterprise).orElseThrow(() -> new ServiceException("企业不存在"));
        return new ReturnVO("行业类目id查询成功", enterprise.getBusinessCategoryId());
    }

    /**
     * 查询企业列表
     *
     * @return
     */
//    public ReturnVO<JgPageVo<JSONArray>> enterList(String enterpriseName,Integer curPage,Integer maxPage) {
    public ReturnVO<JgPageVo<List<JSONObject>>> enterList(AdminQueAnsEnterpriseDto adminQueAnsEnterpriseDto) {
        Page<Object> objects = PageHelper.startPage(adminQueAnsEnterpriseDto.getCurPage(), adminQueAnsEnterpriseDto.getMaxPage());
        QueryWrapper queryWrapper = new QueryWrapper();
        if (StringUtils.isNotBlank(adminQueAnsEnterpriseDto.getEnterpriseName())) {
            queryWrapper.like("enterprise_name", adminQueAnsEnterpriseDto.getEnterpriseName() + "%");
        }
        List<Enterprise> enterprises = enterpriseMapper.selectList(queryWrapper);
        //查询行业类目id
        for (Enterprise enterprise : enterprises) {
            if (enterprise.getBusinessCategoryId() != null) {
                ReturnVO<String> stringReturnVO = evaluationApiFeign.selectBusinessCategoryById(enterprise.getBusinessCategoryId());

                if ("200".equals(stringReturnVO.getCode())) {
                    enterprise.setCategoryName(stringReturnVO.getData());
                }
            }
        }
        List<JSONObject> list = new ArrayList<>();
//        JSONArray jsonArray = new JSONArray();
        enterprises.forEach(model -> {
            JSONObject jsonObject = new JSONObject();
            String enterpriseName1 = model.getEnterpriseName();
            String categoryName = model.getCategoryName();
            Long id = model.getId();
            jsonObject.put("enterpriseName", enterpriseName1);
            jsonObject.put("categoryName", categoryName);
            jsonObject.put("id", id);
            jsonObject.put("createTime", model.getCreateTime());
            list.add(jsonObject);
        });
        long total = objects.getTotal();
        PageInfo pageInfo = new PageInfo(list);
        pageInfo.setTotal(total);
        return new ReturnVO("企业列表查询成功", new JgPageVo<>(pageInfo));

    }

    @Override
    public List<Long> selectAllEnterprise() {
        List<Long> longs = Lists.newArrayList();
        List<Enterprise> enterprises = enterpriseMapper.selectList(new QueryWrapper<>());
        for (Enterprise enterpris : enterprises) {
            longs.add(enterpris.getId());
        }
        return longs;
    }

    @Override
    public FeignEnterpriseDto selectEnterpriseDtoById(Long enterpriseId) {
        FeignEnterpriseDto enterpriseDto = new FeignEnterpriseDto();
        Enterprise enterprise = enterpriseMapper.selectById(enterpriseId);
        if (enterprise == null) {
            return enterpriseDto;
        }
        if (enterprise.getWxUserId() != null) {
            WxUser wxUser = wxUserMapper.selectById(enterprise.getWxUserId());
            if (wxUser != null) {
                enterpriseDto.setPhone(wxUser.getPhone());
            }
        }
        BeanUtils.copyProperties(enterprise, enterpriseDto);
        return enterpriseDto;
    }

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public ReturnVO sendCode(Long enterpriseId) {
        Enterprise enterprise = enterpriseMapper.selectById(enterpriseId);
        Optional.ofNullable(enterprise).orElseThrow(() -> new ServiceException("企业不存在"));
        //院长信息
        WxUser wxUser = wxUserMapper.selectById(enterprise.getWxUserId());
        Optional.ofNullable(wxUser).orElseThrow(() -> new ServiceException("该企业没有院长"));
        if (StringUtils.isBlank(wxUser.getPhone())) {
            throw new ServiceException("该院长没有手机号");
        }
        //发送验证码
        int intFlag = (int) (Math.random() * 1000000);
        String flag = String.valueOf(intFlag);
        if (flag.length() == 6 && flag.substring(0, 1).equals("9")) {
        } else {
            intFlag = intFlag + 100000;
        }
        redisTemplate.opsForValue().set(RedisConstants.PHONE_CODE + enterpriseId + ":" + wxUser.getPhone(), String.valueOf(intFlag));
        SystemMessageMqDto systemMessageMqDto = new SystemMessageMqDto();
        //验证码类短信
        systemMessageMqDto.setSmsType(1);
        systemMessageMqDto.setPhones(
                new ArrayList<String>() {
                    {
                        add(wxUser.getPhone());
                    }
                }
        );
        systemMessageMqDto.setTemplateId(SmsConfig.enterpriseUpdateWxUserId);
        int finalIntFlag = intFlag;//匿名内部类语法规则
        systemMessageMqDto.setParams(new ArrayList<String>() {
            {
                add(String.valueOf(finalIntFlag));
            }
        });
        userMessageProducer.ackMQSender(JSONObject.toJSONString(systemMessageMqDto));
        return new ReturnVO<>("短信发送成功", null);
    }

    @Override
    public void updateEnterpriseStart(Long enterpriseId, Integer star) {
        Enterprise enterprise = enterpriseMapper.selectById(enterpriseId);
        Optional.ofNullable(enterprise).ifPresent(e -> {
            e.setEnterpriseLevel(star);
            enterpriseMapper.updateById(e);
        });
    }

    @Override
    public ReturnVO<Integer> isBanEnterprise(Long enterpriseId) {
        Enterprise enterprise = enterpriseMapper.selectById(enterpriseId);
        if (enterprise == null) {
            return new ReturnVO<>("查看是否禁用成功", 0);
        }
        return new ReturnVO<>("查看是否禁用成功", enterprise.getIsBan());
    }
}
